<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
      class="search-form"
    >
      <el-form-item label="流水号" prop="traceId">
        <el-input
          v-model="queryParams.traceId"
          placeholder="请输入唯一流水号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="关键词" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键词搜索日志"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          type="datetime"
          placeholder="选择开始时间"
          size="small"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 180px"
        />
      </el-form-item>

      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          placeholder="选择结束时间"
          size="small"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 180px"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          class="search-btn"
        >
          搜索
        </el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          class="reset-btn"
        >
          重置
        </el-button>
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefresh"
          class="refresh-btn"
        >
          刷新
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 日志列表 -->
    <div class="log-container">
      <div v-loading="loading" class="log-content">
        <div
          v-for="(log, index) in logList"
          :key="index"
          class="log-item"
          :class="getLogClass(log)"
          @click="handleLogClick(log, index)"
        >
          <div class="log-header">
            <div class="log-index">#{{ getLogIndex(index) }}</div>
            <div
              class="log-trace-id"
              @click.stop="handleTraceIdClick(getTraceId(log))"
              :title="'点击搜索流水号: ' + getTraceId(log)"
            >
              {{ getTraceId(log) }}
            </div>
            <div class="log-level" :class="getLogLevel(log)">
              {{ getLogLevel(log) }}
            </div>
            <div class="log-time">{{ getLogTime(log) }}</div>
            <div class="log-actions">
              <el-button
                type="text"
                icon="el-icon-copy-document"
                @click.stop="handleCopy(log)"
                title="复制"
              />
              <el-button
                type="text"
                icon="el-icon-view"
                @click.stop="handleViewDetail(log, index)"
                title="查看详情"
              />
            </div>
          </div>
          <div class="log-message">
            <pre>{{ getLogMessage(log) }}</pre>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && logList.length === 0" class="empty-state">
          <i class="el-icon-document-remove"></i>
          <p>暂无日志数据</p>
        </div>
      </div>
      
    </div>

    <!-- 日志详情对话框 -->
    <el-dialog
      title="日志详情"
      :visible.sync="detailDialogVisible"
      width="80%"
      class="log-detail-dialog"
      append-to-body
    >
      <div class="log-detail-content">
        <div class="detail-header">
          <el-tag :type="getLogLevelType(currentLog)">
            {{ getLogLevel(currentLog) }}
          </el-tag>
          <span class="detail-trace-id"
            >流水号: {{ getTraceId(currentLog) }}</span
          >
          <span class="detail-time">{{ getLogTime(currentLog) }}</span>
          <span class="detail-index">#{{ currentLogIndex + 1 }}</span>
        </div>
        <div class="detail-message">
          <el-input
            type="textarea"
            :value="getLogMessage(currentLog)"
            :rows="20"
            readonly
            class="log-textarea"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleCopy(currentLog)">
          复制内容
        </el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  </div>
</template>

<script>
import { logList } from "@/api/api/log";
import Pagination from "@/components/Pagination";

export default {
  name: "LogList",
  components: {
    Pagination,
  },
  data() {
    return {
      // 遮罩层
      loading: true,

      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 日志列表数据
      logList: [],
      // 详情对话框
      detailDialogVisible: false,
      currentLog: "",
      currentLogIndex: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        traceId: null,
        keyword: null,
        startTime: null,
        endTime: null,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**
     * 查询日志列表
     */
    getList() {
      this.loading = true;
      const params = { ...this.queryParams };

      logList(params)
        .then((response) => {
          console.log(response, "response");

          // 假设返回的数据格式为 { rows: ['log1', 'log2', ...], total: 100 }
          this.logList = response.list || [];
          this.total = response.total || 0;

          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 获取日志级别
     */
    getLogLevel(log) {
      if (!log) return "INFO";

      const logStr = log.toString().toLowerCase();
      if (logStr.includes("error")) return "ERROR";
      if (logStr.includes("warn")) return "WARN";
      if (logStr.includes("debug")) return "DEBUG";
      return "INFO";
    },

    /**
     * 获取日志级别对应的类型
     */
    getLogLevelType(log) {
      const level = this.getLogLevel(log);
      switch (level) {
        case "ERROR":
          return "danger";
        case "WARN":
          return "warning";
        case "DEBUG":
          return "info";
        default:
          return "success";
      }
    },

    /**
     * 获取日志类名
     */
    getLogClass(log) {
      const level = this.getLogLevel(log).toLowerCase();
      return `log-${level}`;
    },

    /**
     * 获取日志时间
     */
    getLogTime(log) {
      // 尝试从日志中提取时间戳，如果没有则使用当前时间
      const timeRegex = /(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/;
      const match = log.toString().match(timeRegex);
      if (match) {
        return match[1];
      }
      return new Date().toLocaleString();
    },

    /**
     * 获取日志消息内容
     */
    getLogMessage(log) {
      return log.toString();
    },

    /**
     * 获取日志序号
     */
    getLogIndex(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },

    /**
     * 获取流水号
     */
    getTraceId(log) {
      // 尝试从日志中提取流水号，支持多种格式
      const traceRegex =
        /(?:traceId|trace_id|trace-id|requestId|request_id)[:=]\s*([a-zA-Z0-9-_]+)/i;
      const match = log.toString().match(traceRegex);
      if (match) {
        return match[1];
      }
      return "-";
    },

    /**
     * 搜索按钮操作
     */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /**
     * 重置按钮操作
     */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        traceId: null,
        keyword: null,
        startTime: null,
        endTime: null,
      };
      this.handleQuery();
    },

    /**
     * 刷新按钮操作
     */
    handleRefresh() {
      this.getList();
      this.$message.success("刷新成功");
    },

    /**
     * 日志点击事件
     */
    handleLogClick(log, index) {
      // 可以在这里添加日志点击的逻辑
      console.log("点击日志:", log, index);
    },

    /**
     * 流水号点击搜索
     */
    handleTraceIdClick(traceId) {
      if (traceId && traceId !== "-") {
        this.queryParams.traceId = traceId;
        this.queryParams.pageNum = 1;
        this.getList();
        this.$message.success(`已搜索流水号: ${traceId}`);
      }
    },

    /**
     * 查看详情
     */
    handleViewDetail(log, index) {
      this.currentLog = log;
      this.currentLogIndex = index;
      this.detailDialogVisible = true;
    },

    /**
     * 复制日志内容
     */
    handleCopy(log) {
      const content = this.getLogMessage(log);
      if (navigator.clipboard) {
        navigator.clipboard
          .writeText(content)
          .then(() => {
            this.$message.success("复制成功");
          })
          .catch(() => {
            this.fallbackCopy(content);
          });
      } else {
        this.fallbackCopy(content);
      }
    },

    /**
     * 降级复制方法
     */
    fallbackCopy(text) {
      const textArea = document.createElement("textarea");
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.select();
      try {
        document.execCommand("copy");
        this.$message.success("复制成功");
      } catch (err) {
        this.$message.error("复制失败");
      }
      document.body.removeChild(textArea);
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-form {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}



.search-btn {
  background: linear-gradient(to right, #1890ff, #096dd9);
  border: none;
}

.reset-btn {
  border-color: #d9d9d9;
  color: #666;
}

.refresh-btn {
  background: linear-gradient(to right, #52c41a, #389e0d);
  border: none;
}

.log-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.log-content {
  /* 移除最大高度限制，让内容自然显示 */
}

.log-item {
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s;
  cursor: pointer;
}

.log-item:hover {
  background-color: #f8f9fa;
}

.log-item:last-child {
  border-bottom: none;
}

.log-header {
  display: flex;
  align-items: center;
  padding: 12px 20px 8px;
  background-color: #fafbfc;
  border-bottom: 1px solid #eee;
}

.log-index {
  font-size: 12px;
  color: #999;
  margin-right: 15px;
  min-width: 50px;
}

.log-trace-id {
  font-size: 12px;
  color: #1890ff;
  margin-right: 15px;
  min-width: 120px;
  font-family: "Courier New", monospace;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  padding: 2px 6px;
  border-radius: 4px;
}

.log-trace-id:hover {
  background-color: #e6f7ff;
  transform: scale(1.05);
}

.log-level {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  margin-right: 15px;
  min-width: 60px;
  text-align: center;
}

.log-level.INFO {
  background-color: #e6f7ff;
  color: #1890ff;
}

.log-level.WARN {
  background-color: #fff7e6;
  color: #faad14;
}

.log-level.ERROR {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.log-level.DEBUG {
  background-color: #f6ffed;
  color: #52c41a;
}

.log-time {
  font-size: 12px;
  color: #666;
  margin-right: 15px;
  min-width: 140px;
}

.log-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 8px;
}

.log-message {
  padding: 12px 20px;
  background-color: #fff;
}

.log-message pre {
  margin: 0;
  font-family: "Courier New", monospace;
  font-size: 13px;
  line-height: 1.5;
  color: #303133;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.log-info .log-message {
  border-left: 4px solid #1890ff;
}

.log-warn .log-message {
  border-left: 4px solid #faad14;
}

.log-error .log-message {
  border-left: 4px solid #ff4d4f;
}

.log-debug .log-message {
  border-left: 4px solid #52c41a;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state p {
  font-size: 16px;
  margin: 0;
}

.log-detail-dialog {
  .detail-header {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
  }

  .detail-trace-id {
    font-size: 14px;
    color: #1890ff;
    font-family: "Courier New", monospace;
    font-weight: 500;
  }

  .detail-time {
    font-size: 14px;
    color: #666;
  }

  .detail-index {
    font-size: 12px;
    color: #999;
    margin-left: auto;
  }

  .log-textarea {
    font-family: "Courier New", monospace;
  }
}

.dialog-footer {
  text-align: right;
}
</style>
